package com.adnaan.backend.controller.admin;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.adnaan.backend.common.annotation.RestControllerMapping;
import com.adnaan.backend.common.model.PageParams;
import com.adnaan.backend.common.model.Result;
import com.adnaan.backend.entity.Goods;
import com.adnaan.backend.service.GoodsService;
import com.adnaan.backend.utils.AuthUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestControllerMapping("/goods")
@Tag(name = "商品管理", description = "商品管理")
@ApiSupport(author = "adnaan", order = 2)
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    /**
     * 分页查询
     *
     * @param pageParams 分页对象
     * @return 查询结果
     */
    @PostMapping("/page")
    @ApiOperationSupport(order = 2)
    @Operation(summary = "分页查询")
    public Result<Page<Goods>> pageQuery(@RequestBody PageParams<Goods> pageParams) {
        Goods params = pageParams.getParams();
        LambdaQueryWrapper<Goods> lqw = new LambdaQueryWrapper<>();
        lqw.eq(params.getType() != null, Goods::getType, params.getType())
                .eq(params.getStatus() != null, Goods::getStatus, params.getStatus())
                .eq(!AuthUtils.isAdmin(), Goods::getSupplierId, params.getSupplierId())
                .like(StrUtil.isNotBlank(params.getName()), Goods::getName, params.getName())
                .orderByDesc(Goods::getCreateTime);
        return Result.success(goodsService.page(pageParams.getPage(), lqw));
    }

    /**
     * 新增商品
     *
     * @param goods 实例对象
     * @return 实例对象
     */
    @PostMapping("/insert")
    @ApiOperationSupport(order = 3)
    @Operation(summary = "新增商品")
    public Result<Boolean> add(@RequestBody Goods goods) {
        //管理员发布商品则为自营商品
        if (AuthUtils.isAdmin()) {
            goods.setType(0);
        }
        Long userId = StpUtil.getLoginIdAsLong();
        goods.setSupplierId(userId);
        return Result.success(goodsService.save(goods));
    }

    /**
     * 更新商品
     *
     * @param goods 实例对象
     * @return 实例对象
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 4)
    @Operation(summary = "更新商品")
    public Result<Boolean> edit(@RequestBody Goods goods) {
        // 如果是供货商，只能修改自己的商品
        Long userId = StpUtil.getLoginIdAsLong();
        Goods oldGoods = goodsService.getById(goods.getId());
        if (oldGoods == null || !oldGoods.getSupplierId().equals(userId) && !AuthUtils.isAdmin()) {
            return Result.error("您无权修改此商品");
        }
        return Result.success(goodsService.updateById(goods));
    }

    /**
     * 更新商品状态
     *
     * @param id     商品ID
     * @param status 状态：0-下架 1-上架
     * @return 是否成功
     */
    @PostMapping("/status")
    @ApiOperationSupport(order = 5)
    @Operation(summary = "更新商品状态")
    public Result<Boolean> updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        // 如果是供货商，只能修改自己的商品
        Goods goods = goodsService.getById(id);
        if (goods == null) {
            return Result.error("商品不存在");
        }
        Long userId = StpUtil.getLoginIdAsLong();
        if (!goods.getSupplierId().equals(userId) && !AuthUtils.isAdmin()) {
            return Result.error("您无权修改此商品");
        }

        return Result.success(goodsService.updateStatus(id, status));
    }

    /**
     * 删除商品
     *
     * @param id 主键
     * @return 是否成功
     */
    @GetMapping("/delete/{id}")
    @ApiOperationSupport(order = 6)
    @Operation(summary = "删除商品")
    public Result<Boolean> deleteById(@PathVariable Long id) {
        // 如果是供货商，只能删除自己的商品
        Goods goods = goodsService.getById(id);
        if (goods == null) {
            return Result.error("商品不存在");
        }
        Long userId = StpUtil.getLoginIdAsLong();
        if (!goods.getSupplierId().equals(userId) && !AuthUtils.isAdmin()) {
            return Result.error("您无权删除此商品");
        }
        return Result.success(goodsService.removeById(id));
    }
} 